#include "Viewport.h"
#include "Renderable.h"
#include "util.h"
#include "GraphicFactory.h"

namespace Graphics
{
	Viewport::Viewport(void)
	{
		Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
		m_pRect = new Rect(0,0,g->GetWidth(),g->GetHeight());
	}

	Viewport::Viewport(Rect* pRect)
	{
		if(pRect == 0)
		{
			m_pRect = new Rect(pRect->left,pRect->top,pRect->right,pRect->bottom);
		}
		else
		{
			Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
			m_pRect = new Rect(0,0,g->GetWidth(),g->GetHeight());
		}
	}

	Viewport::~Viewport(void)
	{
		delete m_pRect;
	}
	void Viewport::SetRect(const Rect& rect)
	{
		*m_pRect = rect;
	}
	const Rect& Viewport::GetRect(void)
	{
		return *m_pRect;
	}

	bool Viewport::RenderImpl(void)
	{
		Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
		
		// store the rect
		Rect preRect = g->GetRenderRect();
		g->SetRenderRect(this->GetRect());

		bool result = true;
		RenderMap map;

		for(RenderHash::iterator i = m_RenderHash.begin() ; i != m_RenderHash.end(); i++)
		{
			map.insert(*i);
			//result &= (*i).first->Render();
		}

		for(RenderMap::iterator i = map.begin() ; i != map.end(); i++)
		{
			result &= (*i).first->Render();
		}
		
		// recover the rect
		g->SetRenderRect(preRect);
		return result;
	}
	void Viewport::Add(Renderable* const obj)
	{
		if( obj == 0)
		{
			return;
		}

		m_RenderHash[obj];
	}

	void Viewport::Remove(Renderable* const obj)
	{
		m_RenderHash.erase(obj);
	}
}